package wxshop.web.user.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import wxshop.api.user.exception.DataNotFoundException;
import wxshop.api.user.exception.LoginPasswordException;
import wxshop.api.user.model.User;
import wxshop.api.user.service.LoginService;
import wxshop.api.user.service.UserService;
import wxshop.web.user.dto.FormResult;
import wxshop.web.user.tool.JwtTool;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by yvdedu.com on 2018/1/24.
 */
@RestController
public class LoginController {
	
	@Autowired
	private LoginService loginService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private JwtTool jwtTool;
	
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public Object login( @RequestBody User input,HttpServletRequest request) throws JsonProcessingException {
		User user = loginService.login(input);
		System.out.println(user);
		//删除
		if (user!=null) {
			HttpSession session = request.getSession();//登录成功的session
			session.setAttribute("id",user.getId());////登录成功的session
		}
		//删除
		return new FormResult(true,jwtTool.toJwt(user),userService.getUserUrls(input.getId()));
	}
	
	@RequestMapping(value = "zhuce", method = RequestMethod.POST)
	public Object zhuce( @RequestBody User input) throws JsonProcessingException {
		int id = loginService.zhuce(input);
		System.out.println(id);
//		return new FormResult(true,userService.get(user.getId()));
		return new FormResult(true,"注册成功");
	}
	
	@RequestMapping(value = "login", method = RequestMethod.GET)
	public FormResult loginGet(User input) throws JsonProcessingException {
		User user = loginService.login(input);
		return new FormResult(true,jwtTool.toJwt(user),userService.getUserUrls(input.getId()));
	}
	
	//返回的错误消息
	@ExceptionHandler
	public Object on(DataNotFoundException e) {
		return new FormResult(e.getLocalizedMessage());
	}
	
	//返回的错误消息
	@ExceptionHandler
	public Object on(LoginPasswordException e) {
		return new FormResult(e.getLocalizedMessage());
	}
}
